package com.lucifer.cloud.boot.blog.chat.support;

import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.json.JSONUtil;
import com.lucifer.cloud.boot.blog.chat.support.ocr.ZhiPuAiImageRRequest;
import com.lucifer.cloud.boot.blog.chat.support.ocr.ZhiPuAiImageRResponse;
import com.lucifer.cloud.boot.blog.chat.support.ocr.ZhiPuAiImageRUserMessage;
import com.lucifer.cloud.boot.blog.chat.support.video.ZhiPuAiAsyncResponse;
import com.lucifer.cloud.boot.blog.chat.support.video.ZhiPuAiVideoRequest;
import com.lucifer.cloud.boot.blog.chat.support.video.ZhiPuAiVideoResponse;
import com.lucifer.cloud.boot.blog.chat.support.voice.ZhiPuAiVoiceRequest;
import com.lucifer.cloud.boot.blog.chat.support.voice.ZhiPuAiVoiceResponse;
import com.lucifer.cloud.boot.blog.chat.support.voice.ZhiPuAiVoiceUserMessage;
import jakarta.annotation.Resource;
import lombok.SneakyThrows;

import org.springframework.ai.image.Image;
import org.springframework.ai.image.ImageGeneration;
import org.springframework.ai.image.ImagePrompt;
import org.springframework.ai.image.ImageResponse;
import org.springframework.ai.zhipuai.ZhiPuAiImageModel;
import org.springframework.ai.zhipuai.ZhiPuAiImageOptions;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestClient;
import org.springframework.web.multipart.MultipartFile;

import java.util.Base64;
import java.util.List;

/**
 * @author lucifer
 * @date 2025/3/11 9:50
 */
@Service
public class ZhiPuAiSupportApi {

    @Resource(name = "zhiPuAiRestClient")
    private RestClient zhiPuAiRestClient;

    @Resource
    private ZhiPuAiImageModel zhiPuAiImageModel;


    @SneakyThrows
    public String ocr(String message, MultipartFile file) {
        String imgBase64 = Base64.getEncoder().encodeToString(file.getBytes());
        ZhiPuAiImageRUserMessage.ZhiPuAiImageRContent.ZhiPuAiImageRImageUrl image_url = ZhiPuAiImageRUserMessage.ZhiPuAiImageRContent.ZhiPuAiImageRImageUrl.builder().url(imgBase64).build();
        ZhiPuAiImageRUserMessage.ZhiPuAiImageRContent content_image_url = ZhiPuAiImageRUserMessage.ZhiPuAiImageRContent.builder().type("image_url").image_url(image_url).build();
        ZhiPuAiImageRUserMessage.ZhiPuAiImageRContent content_text = ZhiPuAiImageRUserMessage.ZhiPuAiImageRContent.builder().type("text").text(message).build();
        List<ZhiPuAiImageRUserMessage.ZhiPuAiImageRContent> content = org.apache.commons.compress.utils.Lists.newArrayList();
        content.add(content_image_url);
        content.add(content_text);

        ZhiPuAiImageRUserMessage zhiPuAiImageRUserMessage = ZhiPuAiImageRUserMessage.builder()
                .role("user")
                .content(content)
                .build();

        List<ZhiPuAiImageRUserMessage> messages = org.apache.commons.compress.utils.Lists.newArrayList();
        messages.add(zhiPuAiImageRUserMessage);

        ZhiPuAiImageRRequest zhiPuAiImageRRequest = ZhiPuAiImageRRequest.builder().model("glm-4v-flash").messages(messages).user(null).build();
        String zhiPuAiImageRJsonRequest = JSONUtil.toJsonStr(zhiPuAiImageRRequest);
        ResponseEntity<ZhiPuAiImageRResponse> response = ((RestClient.RequestBodySpec) zhiPuAiRestClient.post().uri("/v4/chat/completions", new Object[0])).body(zhiPuAiImageRJsonRequest).retrieve().toEntity(ZhiPuAiImageRResponse.class);
        String text = response.getBody().getChoices().get(0).getMessage().getContent();
        return text;
    }


    public String image(String message, MultipartFile file) {
        ImageResponse response = zhiPuAiImageModel.call(
                new ImagePrompt(message,
                        ZhiPuAiImageOptions.builder()
                                .model("cogview-3-flash")
                                .build())
        );
        ImageGeneration imageGeneration = response.getResult();
        Image image = imageGeneration.getOutput();
        String imageUrl = image.getUrl();
        return imageUrl;
    }


    public String video(String message, MultipartFile file) {
        ZhiPuAiVideoRequest zhiPuAiVideoRequest = ZhiPuAiVideoRequest.builder()
                .model("cogvideox-flash")
                .prompt(message)
                .quality("quality")
                .with_audio(true)
                .size("1920x1080")
                .fps(30)
                .build();
        ResponseEntity<ZhiPuAiVideoResponse> response = ((RestClient.RequestBodySpec) zhiPuAiRestClient.post().uri("/v4/videos/generations", new Object[0])).body(zhiPuAiVideoRequest).retrieve().toEntity(ZhiPuAiVideoResponse.class);
        String id = response.getBody().getId();
        ResponseEntity<ZhiPuAiAsyncResponse> asyncResponse = zhiPuAiRestClient.get().uri("/v4/async-result/{id}", id).retrieve().toEntity(ZhiPuAiAsyncResponse.class);
        while (true) {
            ThreadUtil.sleep(5000);
            asyncResponse = zhiPuAiRestClient.get().uri("/v4/async-result/{id}", id).retrieve().toEntity(ZhiPuAiAsyncResponse.class);
            if (asyncResponse.getBody().getTask_status().equals("SUCCESS")) {
                break;
            }
        }
        return asyncResponse.getBody().getVideo_result().get(0).getUrl();
    }


    @SneakyThrows
    public String voice(String message, MultipartFile file) {
        String voiceBase64 = Base64.getEncoder().encodeToString(file.getBytes());
        ZhiPuAiVoiceUserMessage.ZhiPuAiVoiceContent.ZhiPuAiVoiceAudio audioData = ZhiPuAiVoiceUserMessage.ZhiPuAiVoiceContent.ZhiPuAiVoiceAudio.builder().data(voiceBase64).format("mp3").build();
        ZhiPuAiVoiceUserMessage.ZhiPuAiVoiceContent contentAudio = ZhiPuAiVoiceUserMessage.ZhiPuAiVoiceContent.builder().type("input_audio").input_audio(audioData).build();
        ZhiPuAiVoiceUserMessage.ZhiPuAiVoiceContent contentMessage = ZhiPuAiVoiceUserMessage.ZhiPuAiVoiceContent.builder().type("text").text("text").build();
        List<ZhiPuAiVoiceUserMessage.ZhiPuAiVoiceContent> content = com.google.common.collect.Lists.newArrayList(contentMessage, contentAudio);
        ZhiPuAiVoiceUserMessage mes = ZhiPuAiVoiceUserMessage.builder().role("user").content(content).build();
        List<ZhiPuAiVoiceUserMessage> messages = com.google.common.collect.Lists.newArrayList(mes);

        ZhiPuAiVoiceRequest voiceRequest = ZhiPuAiVoiceRequest.builder()
                .model("glm-4-voice")
//                .system_prompt("""
//                        你只需要将语音转换成文字即可，而不需要对问题进行任何解释
//                        """)
                .messages(messages)
                .max_tokens(1024)
                .stream(false)
                .build();

        String voiceRequestJsonRequest = JSONUtil.toJsonStr(voiceRequest);
        ResponseEntity<ZhiPuAiVoiceResponse> response = ((RestClient.RequestBodySpec) zhiPuAiRestClient.post().uri("/v4/chat/completions", new Object[0])).body(voiceRequestJsonRequest).retrieve().toEntity(ZhiPuAiVoiceResponse.class);
        String text = response.getBody().getChoices().get(0).getMessage().getContent();
        return text;
    }


}
